import java.util.*;

public class Solution2471 {

    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public int minimumOperations(TreeNode root) {
        List<List<Integer>> list=new ArrayList<>();
        dfs(root,0,list);
        int ans=0;
        for (List<Integer> i : list) {
            ans+=cal(i);
        }
        return ans;
    }

    private int cal(List<Integer> list) {
        TreeSet<Integer> set = new TreeSet<>(list);
        int count=0;
        Map<Integer,Integer> map=new HashMap<>();
        for (Integer integer : set) {
            map.put(integer,count++);
        }
        for (int i=0;i<list.size();i++){
            list.set(i,map.get(list.get(i)));
        }
        boolean[] visit=new boolean[list.size()];
        int ans=0;
        for (int i=0;i<list.size();i++){
            visit[i]=true;
            int s=1,t=i;
            while (!visit[list.get(t)]){
                s++;
                t=list.get(t);
                visit[t]=true;
            }
            ans+=s-1;
        }
        return ans;
    }

    private void dfs(TreeNode root, int k, List<List<Integer>> list) {
        if (root==null){
            return;
        }
        if (list.size()==k){
            list.add(new ArrayList<>());
        }
        list.get(k).add(root.val);
        dfs(root.left,k+1,list);
        dfs(root.right,k+1,list);
    }

    public static void main(String[] args) {
        System.out.println(new Solution2471().minimumOperations(new TreeNode(1,new TreeNode(4,new TreeNode(7),new TreeNode(6)),new TreeNode(3,new TreeNode(8,new TreeNode(9),null),new TreeNode(5,new TreeNode(10),null)))));
    }
}
